#include <Windows.h>

#if !OFFICAL_BUILD

bool IsRunningFromStaging(const WCHAR* const command_line)
{
	return !wcscmp(command_line + (wcslen(command_line) - wcslen(L"staging")), L"staging");
}

#endif

int WINAPI WinMain(__in HINSTANCE hInstance, __in_opt HINSTANCE hPrevInstance, 
				   __in_opt LPSTR lpCmdLine, __in int nShowCmd)
{
	UNREFERENCED_PARAMETER(hInstance);
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);
	UNREFERENCED_PARAMETER(nShowCmd);

	WCHAR command_line[MAX_PATH * 2] = {};
	if (0 == ::GetModuleFileName(NULL, command_line, arraysize(command_line)))
		return E_UNEXPECTED;

	::PathRemoveFileSpec(command_line);
#if OFFICIAL_BUILD
	::PathRemoveFileSpec(command_line);
#else
	// This is to facilitate unit tests such as
	// GoogleUpdateCoreTest.LaunchCmdElevated_LocalServerRegistered. If we are
	// running from the staging directory, the shell is in the same directory.
	if (!IsRunningFromStaging(command_line)) 
		::PathRemoveFileSpec(command_line);
#endif
	if (!::PathAppend(command_line, kPCAgentShellFileName))
		return E_UNEXPECTED;

	if (FAILED(StringCchCat(command_line, arraysize(command_line), L" ")) || 
		FAILED(StringCchCat(command_line, arraysize(command_line), CMD_LINE_SWITCH)))
		return E_UNEXPECTED;

	STARTUPINFO si = { sizeof(si) };
	PROCESS_INFORMATION pi = {};
	if (!::CreateProcess(NULL, command_line, Null, NULL, FALSE, 0, NULL, NULL, &si, &pi))
		return E_UNEXPECTED;

	return 0;
}